package com.ganee.agora.view

import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.ganee.agora.R
import com.ganee.agora.model.FileEntity
import com.ganee.agora.model.UpdateUserInfoEntity
import com.ganee.agora.model.UploadFileRequestBody
import com.ganee.agora.model.UserInfoEntity
import com.ganee.agora.utils.ByteUtils.*
import com.ganee.agora.utils.ImgUtils
import com.ganee.agora.utils.Md5Util
import com.ganee.agora.viewmodel.ProfileViewModel
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.cache.ACache
import com.ganee.baselib.httprequest.cache.EnumKey
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.google.gson.Gson
import com.yanzhenjie.album.Action
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.AlbumFile
import com.yanzhenjie.album.api.widget.Widget
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Permission
import kotlinx.android.synthetic.main.activity_profile.*
import kotlinx.android.synthetic.main.toolbar_profile.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File

//个人资料
@Route(path = Constance.ACTIVITY_URL_PROFILE)
class ProfileActivity : BaseActivity<ProfileViewModel>(), View.OnClickListener {

    private var userId:String? = null
    var userPic: String? = null
    override fun getViewModel(): ProfileViewModel {
        return ViewModelProviders.of(this@ProfileActivity).get(ProfileViewModel::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profile)
        ARouter.getInstance().inject(this)
        toolbarCancel.setOnClickListener(this)
        toolbarRight.setOnClickListener(this)
        toolbarTitle.text = "Edit Profile"
        profile_tv_sign_out.setOnClickListener(this)
        profile_avatar.setOnClickListener(this)
        initRequestData()
    }

    private fun initRequestData() {
        viewModel.getUserInfo()
        viewModel.getUserInfoEntity.observe(this, Observer<UserInfoEntity> {
            profile_et_user_name.setText(it.firstName?:"")
            profile_et_nickname.setText(it.lastName?:"")
            profile_et_email.setText(it.email?:"")
            userId = it.userId
            Glide.with(this@ProfileActivity)
                    .load(it.userPic)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .dontAnimate()
                    .thumbnail(0.5f)
                    .placeholder(R.drawable.avatar_placeholder)
                    .error(R.drawable.avatar_placeholder)
                    .into(profile_avatar)
            userPic = it.userPic
        })

    }

    override fun onClick(v: View?) {
        when(v!!.id){
            R.id.toolbarCancel -> {
                finish()
            }
            R.id.toolbarRight -> {
                postUserInfo()
            }
            R.id.profile_tv_sign_out -> {
                ACache.get(this@ProfileActivity).put(EnumKey.User.USER_TOKEN,"")
//                val intent = Intent(this@ProfileActivity,LoginActivity::class.java)
//                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
//                startActivity(intent)
                ARouter.getInstance().build(Constance.ACTIVITY_URL_LOGIN).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
            }
            R.id.profile_avatar -> {
                if (AndPermission.hasPermissions(this, Permission.CAMERA)) {
                    Album.image(this)
                            .singleChoice()
                            .camera(true)
                            .widget(Widget.newLightBuilder(this).statusBarColor(ContextCompat.getColor(this,R.color.color_toolbar)).toolBarColor(ContextCompat.getColor(this,R.color.color_toolbar)).build())
                            .onResult(Action<ArrayList<AlbumFile>>() {
                                initSave(it[0].path)
                            })
                            .onCancel(Action<String>() {

                            })
                            .start()
                }
            }
        }
    }

    private fun initSave(result: String) {
        val fNames = result.substring(result.lastIndexOf("/") + 1)
        val dirFile = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val imgFile: File = if (dirFile == null) {
            File(Environment.getExternalStorageDirectory().path + File.separator
                    + "ganee" + File.separator + fNames)
        } else {
            File(dirFile.absolutePath + File.separator + fNames)
        }
        var path:String? = null
        if (imgFile.exists()) {
            path = imgFile.absolutePath
        } else {
            val bitmap = comp(resizeBitmap(getBitmapForFile(result), 500))

            try {
                path = ImgUtils.saveFile(this, bitmap, fNames)
            } catch (throwable: Throwable) {
                throwable.printStackTrace()
            }

        }

//        baseCode = Md5Util.imgToBase64(path)
        initUploadFile(fNames,path!!)
    }


    /**
     * 上传文件  active/uploadFile  参数：
     */
    private fun initUploadFile(mFileName: String ,path: String) {
        val belongType = "01"
        val fileType = "01"
        val fileContent = Md5Util.imgToBase64(path)
        val infoEntity = UploadFileRequestBody(belongType, fileType, mFileName, fileContent)
        val body = Gson().toJson(infoEntity)
        val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
        viewModel.uploadFile(requestBody)

        viewModel.uploadFile.observe(this, Observer<FileEntity> {
            Glide.with(this)
                    .load(it.filePath)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .centerCrop()
                    .dontAnimate()
                    .placeholder(R.drawable.avatar_placeholder)
                    .error(R.drawable.avatar_placeholder)
                    .thumbnail(0.5f)
                    .into(profile_avatar)
            userPic = it.filePath
        })
    }
    //更新用户信息
    private fun postUserInfo(){
        val firstName = profile_et_user_name.text.toString()
        val lastName = profile_et_nickname.text.toString()
        val email = profile_et_email.text.toString()
        val infoEntity = UpdateUserInfoEntity(userId,userPic,firstName, lastName, email)
        val body = Gson().toJson(infoEntity)
        val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
        viewModel.updateUserInfo(requestBody)
    }
}
